// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化页面数据
    updateStatistics();
    initHealthChart();
    renderDeviceList();

    // 绑定事件监听器
    bindEventListeners();

    // 设置定时更新
    setInterval(updateData, 30000); // 每30秒更新一次数据
});

// 更新统计数据
function updateStatistics() {
    // 更新岸桥数据
    document.getElementById('quayCraneCount').textContent = deviceData.statistics.quayCrane.total;
    document.getElementById('quayCraneRunning').textContent = deviceData.statistics.quayCrane.running;
    document.getElementById('quayCraneIdle').textContent = deviceData.statistics.quayCrane.idle;
    document.getElementById('quayCraneMaintenance').textContent = deviceData.statistics.quayCrane.maintenance;

    // 更新龙门吊数据
    document.getElementById('gantryCraneCount').textContent = deviceData.statistics.gantryCrane.total;
    document.getElementById('gantryCraneRunning').textContent = deviceData.statistics.gantryCrane.running;
    document.getElementById('gantryCraneIdle').textContent = deviceData.statistics.gantryCrane.idle;
    document.getElementById('gantryCraneMaintenance').textContent = deviceData.statistics.gantryCrane.maintenance;

    // 更新AGV数据
    document.getElementById('agvCount').textContent = deviceData.statistics.agv.total;
    document.getElementById('agvRunning').textContent = deviceData.statistics.agv.running;
    document.getElementById('agvIdle').textContent = deviceData.statistics.agv.idle;
    document.getElementById('agvMaintenance').textContent = deviceData.statistics.agv.maintenance;
}

// 初始化健康度图表
function initHealthChart() {
    const chart = echarts.init(document.getElementById('healthChart'));
    const option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: deviceData.healthData.categories,
            axisLabel: {
                color: '#7f8c8d'
            }
        },
        yAxis: {
            type: 'value',
            max: 100,
            axisLabel: {
                color: '#7f8c8d'
            }
        },
        series: [{
            data: deviceData.healthData.data,
            type: 'bar',
            itemStyle: {
                color: '#1e3799'
            },
            label: {
                show: true,
                position: 'top',
                color: '#2c3e50'
            }
        }]
    };
    chart.setOption(option);
}

// 渲染设备列表
function renderDeviceList(filteredDevices = deviceData.devices) {
    const deviceList = document.getElementById('deviceList');
    deviceList.innerHTML = '';

    filteredDevices.forEach(device => {
        const deviceElement = createDeviceElement(device);
        deviceList.appendChild(deviceElement);
    });
}

// 创建设备元素
function createDeviceElement(device) {
    const div = document.createElement('div');
    div.className = 'device-item';
    div.dataset.id = device.id;

    const statusClass = {
        running: 'running',
        idle: 'idle',
        maintenance: 'maintenance'
    }[device.status];

    div.innerHTML = `
        <div class="device-item-header">
            <span class="device-item-title">${device.name}</span>
            <span class="device-item-status ${statusClass}">${getStatusText(device.status)}</span>
        </div>
        <div class="device-item-info">
            <span>位置：${device.location}</span>
            <span>运行时长：${device.runtime}</span>
            <span>电量：${device.battery}</span>
        </div>
    `;

    return div;
}

// 获取状态文本
function getStatusText(status) {
    const statusMap = {
        running: '运行中',
        idle: '待机中',
        maintenance: '维护中'
    };
    return statusMap[status] || status;
}

// 显示设备详情
function showDeviceDetail(device) {
    const detailPanel = document.querySelector('.device-detail');
    detailPanel.classList.add('active');

    // 更新基本信息
    document.getElementById('deviceId').textContent = device.id;
    document.getElementById('deviceType').textContent = getDeviceTypeText(device.type);
    document.getElementById('deviceLocation').textContent = device.location;
    document.getElementById('deviceStatus').textContent = getStatusText(device.status);
    document.getElementById('deviceRuntime').textContent = device.runtime;
    document.getElementById('deviceBattery').textContent = device.battery;

    // 更新图表
    initStatusTrendChart(device);
    initBatteryTrendChart(device);
}

// 获取设备类型文本
function getDeviceTypeText(type) {
    const typeMap = {
        quayCrane: '岸桥',
        gantryCrane: '龙门吊',
        agv: 'AGV'
    };
    return typeMap[type] || type;
}

// 初始化状态趋势图表
function initStatusTrendChart(device) {
    const chart = echarts.init(document.getElementById('statusTrendChart'));
    const option = {
        tooltip: {
            trigger: 'axis'
        },
        xAxis: {
            type: 'category',
            data: device.statusTrend.times,
            axisLabel: {
                color: '#7f8c8d'
            }
        },
        yAxis: {
            type: 'value',
            max: 1,
            axisLabel: {
                color: '#7f8c8d'
            }
        },
        series: [{
            data: device.statusTrend.values,
            type: 'line',
            smooth: true,
            itemStyle: {
                color: '#1e3799'
            },
            areaStyle: {
                opacity: 0.3
            }
        }]
    };
    chart.setOption(option);
}

// 初始化电量趋势图表
function initBatteryTrendChart(device) {
    const chart = echarts.init(document.getElementById('batteryTrendChart'));
    const option = {
        tooltip: {
            trigger: 'axis'
        },
        xAxis: {
            type: 'category',
            data: device.batteryTrend.times,
            axisLabel: {
                color: '#7f8c8d'
            }
        },
        yAxis: {
            type: 'value',
            max: 100,
            axisLabel: {
                color: '#7f8c8d'
            }
        },
        series: [{
            data: device.batteryTrend.values,
            type: 'line',
            smooth: true,
            itemStyle: {
                color: '#2ecc71'
            },
            areaStyle: {
                opacity: 0.3
            }
        }]
    };
    chart.setOption(option);
}

// 绑定事件监听器
function bindEventListeners() {
    // 设备列表点击事件
    document.getElementById('deviceList').addEventListener('click', function(e) {
        const deviceItem = e.target.closest('.device-item');
        if (deviceItem) {
            const deviceId = deviceItem.dataset.id;
            const device = deviceData.devices.find(d => d.id === deviceId);
            if (device) {
                // 更新选中状态
                document.querySelectorAll('.device-item').forEach(item => {
                    item.classList.remove('active');
                });
                deviceItem.classList.add('active');

                // 显示详情
                showDeviceDetail(device);
            }
        }
    });

    // 关闭详情按钮事件
    document.getElementById('closeDetail').addEventListener('click', function() {
        document.querySelector('.device-detail').classList.remove('active');
        document.querySelectorAll('.device-item').forEach(item => {
            item.classList.remove('active');
        });
    });

    // 筛选器变化事件
    document.getElementById('deviceTypeFilter').addEventListener('change', filterDevices);
    document.getElementById('statusFilter').addEventListener('change', filterDevices);
}

// 筛选设备
function filterDevices() {
    const typeFilter = document.getElementById('deviceTypeFilter').value;
    const statusFilter = document.getElementById('statusFilter').value;

    let filteredDevices = deviceData.devices;

    if (typeFilter !== 'all') {
        filteredDevices = filteredDevices.filter(device => device.type === typeFilter);
    }

    if (statusFilter !== 'all') {
        filteredDevices = filteredDevices.filter(device => device.status === statusFilter);
    }

    renderDeviceList(filteredDevices);
}

// 更新所有数据
function updateData() {
    // 模拟数据更新
    deviceData.devices.forEach(device => {
        // 更新运行时长
        const runtime = parseFloat(device.runtime);
        device.runtime = (runtime + 0.5).toFixed(1) + '小时';

        // 更新电量
        const battery = parseInt(device.battery);
        device.battery = Math.max(0, battery - Math.floor(Math.random() * 3)) + '%';

        // 更新趋势数据
        device.statusTrend.times.push(new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }));
        device.statusTrend.values.push(Math.random() > 0.1 ? 1 : 0);
        device.batteryTrend.times.push(new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }));
        device.batteryTrend.values.push(parseInt(device.battery));

        // 保持最近5个数据点
        if (device.statusTrend.times.length > 5) {
            device.statusTrend.times.shift();
            device.statusTrend.values.shift();
            device.batteryTrend.times.shift();
            device.batteryTrend.values.shift();
        }
    });

    // 更新显示
    updateStatistics();
    initHealthChart();
    renderDeviceList();

    // 如果详情面板打开，更新图表
    const activeDevice = document.querySelector('.device-item.active');
    if (activeDevice) {
        const deviceId = activeDevice.dataset.id;
        const device = deviceData.devices.find(d => d.id === deviceId);
        if (device) {
            initStatusTrendChart(device);
            initBatteryTrendChart(device);
        }
    }
}